import React from 'react'
import menuRoute from 'routes/menuRoute'
import moment from 'moment'
import configureStore from "stores"
import { setOrderManagement } from "actions/cache"
import { deepFullCopy, dealCache , messages } from "share/common";
import { connect } from 'react-redux'

import { Tabs, Button, Row, Col, Popover, Popconfirm, message } from 'antd';
const TabPane = Tabs.TabPane;
import ResizeTable from 'components/resize-table';
import SearchArea from 'components/search-area'
import 'styles/order-management/order-management.scss'
import orderService from 'containers/increment-service/order-management/order-management.service'

let serviceTypeCode = {
  id :'serviceTypeCode',
  single: true,
  items: [
    {
      label: messages('order-management.key68')/*服务大类*/,
      key: 'serviceTypeCode',
      checked: ['ALL'],
      options: [{label: messages('common.all')/*全部*/,  value: 'ALL'},]
    }]
};
let invoiceStatus = {
  id: 'invoiceStatus',
  single: true,
  items: [
    {
      label: messages('order-management.key70')/*开票状态*/,
      key: 'invoiceStatus',
      checked: ['ALL'],
      options: [
        {label: messages('common.all')/*全部*/,  value: 'ALL'},
        {label: messages('order-management.key71')/*未申请*/,  value: 'NON_INVOICE'},
        {label: messages('order-management.key72')/*待开票*/,  value: 'WAIT_INVOICE'}
        ]
    }]
};
  class OrderManagement extends React.Component {
  constructor(props) {
    super(props);
    this.orderType = {
      NEW_BUY: messages('order-management.key81')/*新购*/,
      ADD_BUY: messages('order-management.key67')/*加购*/,
      RENEWAL: messages('order-management.key78')/*续费*/,
    };
    this.statusNote = {
      WAIT_PAYMENT: messages('order-management.key1')/*待付款*/,
      WAIT_CONFIRM_PAYMENT: messages('order-management.key61')/*待确认付款*/,//(客户点击已付款按钮后的标记)
      WAIT_EFFECTIVE: messages('order-management.key62')/*待生效*/,
      USING: messages('order-management.key63')/*使用中*/,
      BEYOND_UPPER_LIMIT: messages('order-management.key64')/*超上限*/,
      NON_PAYMENT_OVERTIME: messages('order-management.key65')/*超时未付*/,
      EXPIRED: messages('order-management.key66')/*到期*/,
      CANCEL: messages('common.cancel')/*取消*/,
      ADD_BUY: messages('order-management.key67')/*加购*/,
      ONLINE_CLOSED: messages('order-management.key82')/*线上关闭*/,//(线上关闭支付订单)
      ONLINE_REFUND: messages('order-management.key83')/*线上退款*/,//(线上订单退款)
    };
    this.state = {
      loading: false,
      tabs: [
        {tab: messages('common.all')/*全部*/, key: 'ALL'},
        {tab: messages('order-management.key1')/*待付款*/, key: 'WAIT_PAYMENT'},
        {tab: messages('order-management.key2')/*已付款*/, key: 'PAID'},
        {tab: messages('order-management.key3')/*已关闭*/, key: 'CLOSED'}
      ],
      activeTab: 'ALL',
      searchForm: [
        {type: 'input', id: 'orderCode', label: messages('order-management.key12')/*订单编号*/, placeholder: messages('order-management.key58')/*请输入订单编号*/},
        {type: 'input', id: 'serviceName', label: messages('order-management.key13')/*服务名称*/, placeholder: messages('order-management.key59')/*请输入服务名称*/}
      ],
      searchRadio: {
        ALL: [
          {id: 'subStatus', single: true, items: [{label: messages('order-management.key60')/*订单子状态*/, key: 'subStatus', checked: ['ALL'], options: [
            {label: messages('common.all')/*全部*/,  value: 'ALL'},
            {label: messages('order-management.key1')/*待付款*/,  value: 'WAIT_PAYMENT'},
            {label: messages('order-management.key61')/*待确认付款*/,  value: 'WAIT_CONFIRM_PAYMENT'},
            {label: messages('order-management.key62')/*待生效*/,  value: 'WAIT_EFFECTIVE'},
            {label: messages('order-management.key63')/*使用中*/,  value: 'USING'},
            {label: messages('order-management.key64')/*超上限*/,  value: 'BEYOND_UPPER_LIMIT'},
            {label: messages('order-management.key65')/*超时未付*/,  value: 'NON_PAYMENT_OVERTIME'},
            {label: messages('order-management.key66')/*到期*/,  value: 'EXPIRED'},
            {label: messages('order-management.key67')/*加购*/,  value: 'ADD_BUY'},
            {label: messages('common.cancel')/*取消*/,  value: 'CANCEL'}
          ]}]},
          serviceTypeCode,
          invoiceStatus,
        ],
        WAIT_PAYMENT: [
          {id: 'subStatus', single: true, items: [{label: messages('order-management.key60')/*订单子状态*/, key: 'subStatus', checked: ['ALL'], options: [
            {label: messages('common.all')/*全部*/,  value: 'ALL'},
            {label: messages('order-management.key1')/*待付款*/,  value: 'WAIT_PAYMENT'},
            {label: messages('order-management.key61')/*待确认付款*/,  value: 'WAIT_CONFIRM_PAYMENT'}
          ]}]},
          serviceTypeCode,
          invoiceStatus,
        ],
        PAID: [
          {id: 'subStatus', single: true, items: [{label: messages('order-management.key60')/*订单子状态*/, key: 'subStatus', checked: ['ALL'], options: [
            {label: messages('common.all')/*全部*/,  value: 'ALL'},
            {label: messages('order-management.key62')/*待生效*/,  value: 'WAIT_EFFECTIVE'},
            {label: messages('order-management.key63')/*使用中*/,  value: 'USING'}
          ]}]},
          serviceTypeCode,
          invoiceStatus,
        ],
        CLOSED: [
          {id: 'subStatus', single: true, items: [{label: messages('order-management.key60')/*订单子状态*/, key: 'subStatus', checked: ['ALL'], options: [
            {label: messages('common.all')/*全部*/,  value: 'ALL'},
            {label: messages('order-management.key64')/*超上限*/,  value: 'BEYOND_UPPER_LIMIT'},
            {label: messages('order-management.key65')/*超时未付*/,  value: 'NON_PAYMENT_OVERTIME'},
            {label: messages('order-management.key66')/*到期*/,  value: 'EXPIRED'},
            {label: messages('order-management.key67')/*加购*/,  value: 'ADD_BUY'},
            {label: messages('common.cancel')/*取消*/,  value: 'CANCEL'}
          ]}]},
          serviceTypeCode,
          invoiceStatus,
        ]
      },
      searchParams: {},
      columns: [
        {title: messages('order-management.key12')/*订单编号*/, dataIndex: 'orderCode', width: '12%',render: text => {
      return(
        <Popover content={text}
                 placement="topLeft"
                 overlayStyle={{maxWidth: 500}}>
          {text}
        </Popover>
      )
    }},
        {title: messages('order-management.key13')/*服务名称*/, dataIndex: 'serviceName', render: value => (
          <Popover content={value}
                   placement="topLeft"
                   overlayStyle={{maxWidth: 500}}>
            <span className="service-name-column">{value}</span>
          </Popover>
        )},
        {title: messages('order-management.key68')/*服务大类*/, dataIndex: 'serviceTypeName', render: text => {
          return(
            <Popover content={text}
                     placement="topLeft"
                     overlayStyle={{maxWidth: 500}}>
              {text}
            </Popover>
          )
          }},
        {title: messages('order-management.key16')/*订单类型*/, dataIndex: 'orderTypeName',render: text => {
            return(
              <Popover content={text}
                       placement="topLeft"
                       overlayStyle={{maxWidth: 500}}>
                {text}
              </Popover>
            )
          }},
        {title: messages('order-management.key17')/*订单状态*/, dataIndex: 'statusName', render: text => {
            return(
              <Popover content={text}
                       placement="topLeft"
                       overlayStyle={{maxWidth: 500}}>
                {text}
              </Popover>
            )
          }},
        {title: messages('order-management.key73')/*子状态*/, dataIndex: 'subStatus',render: text => {
            return(
              <Popover content={this.statusNote[text]}
                       placement="topLeft"
                       overlayStyle={{maxWidth: 500}}>
                {this.statusNote[text]}
              </Popover>
            )
          }},
        {title: messages('order-management.key74')/*创建日期*/, dataIndex: 'createdDate', render: text => {
      return(
        <Popover content={moment(text).format('YYYY-MM-DD')}
                 placement="topLeft"
                 overlayStyle={{maxWidth: 500}}>
          {moment(text).format('YYYY-MM-DD')}
        </Popover>
      )
    }},
        {title: messages('common.amount')/*金额*/, dataIndex: 'actualAmount', width: '13%', render: this.filterMoney},
        {title: messages('order-management.key70')/*开票状态*/, dataIndex: 'invoiceStatus',render: text => {
            return(
              <Popover content={text === "WAIT_INVOICE" ? messages('order-management.key72')/*待开票*/ : messages('order-management.key71')/*未申请*/}
                       placement="topLeft"
                       overlayStyle={{maxWidth: 500}}>
                {text === "WAIT_INVOICE" ? messages('order-management.key72')/*待开票*/ : messages('order-management.key71')/*未申请*/}
              </Popover>
            )
          }},
        {title: messages('common.operation')/*操作*/, dataIndex: 'id', width: '15%', render: (value, record, index) => (
          <div className="operate-column">
            <Row>
              <Col span={12}><a>{messages('order-management.key75')/*查看详情*/}</a></Col>
              <Col span={6}><a className={record.payFlag ? '' : 'disabled'}
                               onClick={e => this.toPay(e, value, record.payFlag)}>{messages('order-management.key76')/*支付*/}</a></Col>
              <Col span={6}>
                {record.cancelFlag ? (
                  <Popconfirm title={messages('order-management.key77')/*确定取消吗*/}
                              placement="topRight"
                              overlayStyle={{minWidth: 150}}
                              onConfirm={() => this.toCancel(record, index)}>
                    <a onClick={e => e.stopPropagation()}>{messages('common.cancel')/*取消*/}</a>
                  </Popconfirm>
                ) : (
                  <a className='disabled' onClick={e => e.stopPropagation()}>{messages('common.cancel')/*取消*/}</a>
                )}
              </Col>
            </Row>
            <Row>
              <Col span={12}><a className={record.applyInvoiceFlag ? '' : 'disabled'}
                                onClick={e => this.toApplyInvoice(e, value, record.applyInvoiceFlag)}>{messages('order-management.key57')/*申请开票*/}</a></Col>
              {/*<Col span={6}><a>{messages('order-management.key78')}</a></Col>*/}
              {/*<Col span={6}><a>{messages('order-management.key67')}</a></Col>*/}
            </Row>
          </div>
        )}
      ],
      data: [],
      page: 0,
      size: 10,
      pagination: {
        total: 0,
      },
      cacheSearchData: {}, //缓存筛选的数据
      orderDetail: menuRoute.getRouteItem('order-management-detail'), //订单详情
      serviceList: menuRoute.getRouteItem('senior-service-open'), //服务列表
      orderPay: menuRoute.getRouteItem('order-pay'), //订单支付页面
    }
  }
  componentWillMount() {
    /* todo 后端下个迭代上这个接口 */
    this.getServiceType()
  }

  componentDidMount() {
    this.getCache()
  }

  getServiceType = () => {
    const {searchRadio} = this.state;
    let params = {
      // customEnumerationType: 'OPERATION',
      codes: 'PAID_SERVICE_CLASSIFICATION',
    };
    orderService.getServiceType(params).then(res => {
      let arr = [];
      res.data.PAID_SERVICE_CLASSIFICATION.map(item => {
        arr.push({label: item.name,  value: item.code})
      });
      for(let attr in searchRadio){
        let item = searchRadio[attr][1].items[0].options;
        item = item.concat(arr);
        searchRadio[attr][1].items[0].options = item;
      }
      this.setState({
        searchRadio,
      })
    })
  };
  //存储筛选数据缓存
  setCache = (result) =>{
    const { activeTab, page } = this.state;
    result.tab = activeTab;
    result.page = page;
    this.setState({ cacheSearchData: result })
  };

  //获取筛选数据缓存
  getCache = () => {
    let result = this.props.orderManagement;
    if (result && JSON.stringify(result) !== "{}") {
      this.setState({ cacheSearchData: result },() => {
        this.dealCache(result)
      })
    } else {
      this.getList()
    }
  };

  //处理筛选缓存数据
  dealCache = (result) => {
    const { searchForm } = this.state;
    if (result) {
      dealCache(searchForm, result);
      let searchRadio = this.state.searchRadio;
      searchRadio[result.tab].map(radioItem => {
        Object.keys(result).map(key => {
          if (radioItem.id === key) {
            radioItem.items[0].checked = [result[key] || 'ALL']
          }
        })
      });
      this.setState({
        activeTab: result.tab,
        page: result.page,
        searchRadio
      }, () => {
        this.search(result);
        configureStore.store.dispatch(setOrderManagement(null));
      })
    }
  };

  getList = () => {
    const { activeTab, page, size, searchParams } = this.state;
    let params = deepFullCopy(searchParams);
    params.page = page;
    params.size = size;
    activeTab !== 'ALL' && (params.status = activeTab);
    this.setState({ loading: true });
    orderService.getOrderList(params).then(res => {
      this.setState({
        loading: false,
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          current: page + 1,
          onChange: this.onChangePaper
        }
      })
    })
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.setCache(this.state.cacheSearchData);
        this.getList()
      })
    }
  };

  //搜索
  search = (values) => {
    this.setCache({...values});
    values.subStatus === 'ALL' && (values.subStatus = '');
    values.serviceTypeCode === 'ALL' && (values.serviceTypeCode = '');
    values.invoiceStatus === 'ALL' && (values.invoiceStatus = '');
    this.setState({
      searchParams: values,
      page: 0,
    }, () => {
      this.getList()
    })
  };

  clear = () => {
    this.setCache({});
    this.setState({
      searchParams: {},
      cacheSearchData: {},
    }, () => {
      this.getList()
    })
  };

  handleTabChange = (value) => {
    let searchRadio = this.state.searchRadio;
    Object.keys(searchRadio).map(key => {
      searchRadio[key].map(radioItem => {
        radioItem.items[0].checked = ['ALL']
      })
    });
    this.setState({
      page: 0,
      activeTab: value,
      searchParams: {},
      searchRadio
    }, () => {
      this.setCache({});
      this.getList()
    })
  };

  //操作 - 支付
  toPay = (e, id, flag) => {
    e.stopPropagation();
    configureStore.store.dispatch(setOrderManagement(this.state.cacheSearchData));
    flag && this.context.router.push(this.state.orderPay.url.replace(':orderId', id))
  };

  //操作 - 取消
  toCancel = (record, index) => {
    this.setState({ loading: true });
    record.status = 'CLOSED';
    orderService.updateOrderStatus(record).then(res => {
      let data = this.state.data;
      res.data.serviceTypeName = record.serviceTypeName;
      res.data.orderTypeName = record.orderTypeName;
      res.data.invoiceStatusName = record.invoiceStatusName;
      res.data.subStatusName = messages('common.cancel')/*取消*/;
      data[index] = res.data;
      this.setState({ loading: false, data });
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  //操作 - 申请开票
  toApplyInvoice = (e, id, flag) => {
    e.stopPropagation();
    configureStore.store.dispatch(setOrderManagement(this.state.cacheSearchData));
    flag && this.context.router.push(this.state.orderDetail.url.replace(':id', id) + '?tab=invoice')
  };

  handleRowClick = (record) => {
    configureStore.store.dispatch(setOrderManagement(this.state.cacheSearchData));
    this.context.router.push(this.state.orderDetail.url.replace(':id', record.id))
  };

  //去下单
  toOpenService = () => {
    this.context.router.push(this.state.serviceList.url)
  };

  //搜索模块渲染
  renderSearchArea = () => {
    const { searchForm, searchRadio, activeTab } = this.state;
    return (
      <SearchArea searchForm={searchForm}
                  checkboxListForm={searchRadio[activeTab]}
                  submitHandle={this.search}
                  clearHandle={this.clear}
      />
    )
  };

  render(){
    const { loading, tabs, activeTab, columns, data, pagination } = this.state;
    return (
      <div className="order-management">
        <Tabs type="card" activeKey={activeTab} onChange={this.handleTabChange}>
          {tabs.map(item => <TabPane tab={item.tab} key={item.key} />)}
        </Tabs>
        {activeTab === 'ALL' && this.renderSearchArea()}
        {activeTab === 'WAIT_PAYMENT' && this.renderSearchArea()}
        {activeTab === 'PAID' && this.renderSearchArea()}
        {activeTab === 'CLOSED' && this.renderSearchArea()}
        <div className="table-header">
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.toOpenService}>{messages('order-management.key79')/*去下单*/}</Button>
          </div>
          <div className="table-header-title"> {messages('order-management.key80',{arg1:pagination.total})/*共搜索到{arg1}条数据*/}
          </div>
        </div>
        <ResizeTable
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          size="middle"
          bordered
        />
      </div>
    )
  }

}

OrderManagement.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    orderManagement: state.cache.orderManagement
  }
}

export default connect(mapStateToProps)(OrderManagement);
